package com.bitdf.txing.users.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bitdf.txing.users.vo.UserRoleQueryVo;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bitdf.txing.common.utils.PageUtils;
import com.bitdf.txing.common.utils.Query;

import com.bitdf.txing.users.dao.UserRoleDao;
import com.bitdf.txing.users.entity.UserRoleEntity;
import com.bitdf.txing.users.service.UserRoleService;
import org.springframework.transaction.annotation.Transactional;


@Service("userRoleService")
public class UserRoleServiceImpl extends ServiceImpl<UserRoleDao, UserRoleEntity> implements UserRoleService {

    /**
     * 分页查询
     *
     * @param queryVo
     * @return
     */
    @Override
    public PageUtils queryPage(UserRoleQueryVo queryVo) {
        LambdaQueryWrapper<UserRoleEntity> wrapper = new QueryWrapper<UserRoleEntity>().lambda().like(queryVo.getName() != null, UserRoleEntity::getName, queryVo.getName())
                .eq(queryVo.getDefaultRole() != null, UserRoleEntity::getDefaultRole, queryVo.getDefaultRole());

        IPage<UserRoleEntity> page = this.page(
                new Query<UserRoleEntity>().getPage(queryVo),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 保存角色
     *
     * @param userRole
     * @return
     */
    @Override
    @Transactional
    public boolean saveRole(UserRoleEntity userRole) {
        if (userRole.getDefaultRole() == 1) {
            UserRoleEntity entity = this.getOne(new QueryWrapper<UserRoleEntity>().lambda().eq(UserRoleEntity::getDefaultRole, 1));
            if (entity != null) {
                // 如果默认的用户角色已存在，则把原来的默认角色改为非默认
                entity.setDefaultRole(0);
                this.updateById(entity);
            }
        }
        this.save(userRole);
        return true;
    }

    /**
     * 更新角色
     *
     * @param userRole
     * @return
     */
    @Override
    @Transactional
    public boolean updateRole(UserRoleEntity userRole) {
        if (userRole.getDefaultRole() == 1) {
            UserRoleEntity entity = this.getOne(new QueryWrapper<UserRoleEntity>().lambda().eq(UserRoleEntity::getDefaultRole, 1));
            if (entity != null && !entity.getId().equals(userRole.getId())) {
                // 如果默认的用户角色已存在，则把原来的默认角色改为非默认
                entity.setDefaultRole(0);
                this.updateById(entity);
            }
        }
        boolean b = this.updateById(userRole);
        return b;
    }

}